home *** CD-ROM | disk | FTP | other *** search
- Path: cymbal.aix.calpoly.edu!not-for-mail
- From: dstubbs@cymbal.aix.calpoly.edu (Dan Stubbs)
- Newsgroups: comp.lang.c
- Subject: Re: quick decision: is n a power of 2?
- Date: 22 Jan 1996 16:34:19 -0800
- Organization: California Polytechnic State University, San Luis Obispo
- Message-ID: <4e1aeb$1gl8@cymbal.aix.calpoly.edu>
- References: <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca>
- NNTP-Posting-User: dstubbs@cymbal.aix.calpoly.edu
-
- In article <Pine.OSF.3.91.960119114608.18779E-100000@io.UWinnipeg.ca>,
- Bill Simpson <wsimpson@uwinnipeg.ca> wrote:
-
- >Is there a fast way to decide whether a number n is a power of 2?
-
- --[text deleted]
- >
- >Bill Simpson
-
- There have been many responces to this post. I have selected four
- approaches to solving this problem and implemented them using
- a "common" coding approach. I timed these implementations by
- ^^^^^
- measuring the time to search the first 500,000 integers for
- powers of two. I performed these measurements on four different
- combinations of compiler/hardware. The four times (normalized)
- are shown as a comment with each of the implementations. In each
- case the compiler was to its highest optimization level.
- (The times are normalized with respect to each of the four
- compiler/hardware combinations.)
-
- Here are four of the approaches that were posted--along with
- the results of a few simple timing studies.
-
- Implementation Normalized Execution Times
- ---------------- ----------------------------
-
- int is_power_of_two(int k) { /* 1.0 1.0 1.0 1.0 */
- if (k <= 0) return 0;
- return (!(k & (k-1)));
- }
-
- int is_power_of_two(int k) { /* 1.1 1.0 1.1 1.0 */
- if (k <= 0) return 0;
- return ((k & (k-1)) == 0);
- }
-
- int is_power_of_two(int k) { /* 1.9 1.4 1.5 1.3 */
- if (k <= 0) return 0;
- while (k > 0) {
- if (k & 1)
- return (k > 1) ? 0 : 1;
- k >>= 1;
- }
- }
-
- int is_power_of_two(int k) { /* 7.1 5.8 5.1 3.6 */
- int j;
- if (k<=0) return 0;
- for (j=0; k; k >>= 1)
- if (k&1) ++j;
- return (j == 1) ? 1 : 0;
- }
-
-